/**
 * Created by 83617 on 2019/1/7.
 */
var mongoose = require('mongoose')
var bcrypt = require('bcryptjs')
var salt_work_factor = 10

var userSchema = new mongoose.Schema({
    username:{
        unique:true,
        type:String
    },
    password:String,
    meta:{
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    }
})

userSchema.pre('save',function(next){
    var user = this
    if(this.isNew){
        this.meta.createAt = this.meta.updateAt = Date.now()
    }else{
        this.meta.updateAt = Date.now()
    }
    bcrypt.genSalt(salt_work_factor,function(err,salt){   //generate salt
        if(err) return next(err)
        bcrypt.hash(user.password,salt,function(err,hash){   //mix password with the salt
            if(err) return next(err)
            user.password = hash
            next()
        })
    })
})

userSchema.methods = {
    comparePassword:function(_password,cb){
        bcrypt.compare(_password,this.password,function(err,isMatch){
            if(err) return cb(err)
            cb(null,isMatch)
        })
    }
}

userSchema.statics = {
    fetch:function(cb){

    },
    findByName:function(username,cb){
        return this
            .findOne({username:username})
            .exec(cb)
    }
}

module.exports = userSchema